﻿/*
 * Copyright 2008 Lucifer Lu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections;
using System.Windows;
using System.Windows.Browser;
using SilverChart.Configuration;
using SilverChart.Core.Log;
using SilverChart.JsonConfiguration;
using SilverChart.Core;
using System.Json;
using SilverChart.Core.Service;
using SilverChart.Core.Configuration;

namespace SilverChart {
    public partial class App : Application {
        public App() {
            this.Startup += this.OnStartup;
            this.Exit += this.OnExit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void OnStartup(object sender, StartupEventArgs e) {
            String JsonData = "";
            if (e.InitParams.ContainsKey("onGetData")) {
                String onGetDataEventHandler = e.InitParams["onGetData"];
                try {
                    JsonData = (String)HtmlPage.Window.Invoke(onGetDataEventHandler, new Object[] { });
                }
                catch (InvalidOperationException ex) {
                    String ErrorMessage = "Invoke '" + onGetDataEventHandler + "' method error:\n";
                    ErrorMessage += ex.Message;
                    ErrorMessage += "\n";
                    ErrorMessage += "Data:";
                    IDictionary map = ex.Data;
                    ICollection keys = map.Keys;
                    foreach (Object key in keys) {
                        ErrorMessage += "\t";
                        String value = map[key].ToString();
                        ErrorMessage += key.ToString();
                        ErrorMessage += ":";
                        ErrorMessage += value;
                        ErrorMessage += "\n";
                    }
                    ErrorMessage += "\n";
                    ErrorMessage += ex.StackTrace;
                    HtmlPage.Window.Alert(ErrorMessage);
                }
                catch (Exception ex) {
                    String ErrorMessage = "Invoke '" + onGetDataEventHandler + "' method error:\n";
                    ErrorMessage += ex.Message;
                    ErrorMessage += "\n";
                    ErrorMessage += ex.StackTrace;
                    HtmlPage.Window.Alert(ErrorMessage);
                }
            }

            LoggerConfigurations logConfig = new LoggerConfigurations();
#if (DEBUG || UNIT_TEST)
            logConfig.CreateLogDiv = true;
            logConfig.GlobalLogLevel = LogLevel.Debug;
            logConfig.Loggers.Add("*");
#endif
            Logger.Initialize(logConfig);
            Logger logger = Logger.GetLogger<App>();
            try {
                AppDomainHelper.Initialize();
            }
            catch (Exception ex) {
                logger.Debug(ex.Message);
            }

            logger.Debug("Totoal Assemblies:" + AppDomainHelper.Instance.AssemblyCount);
            if (JsonData != null) {
                ConfigurationItem conf = ServiceManager.Instance.GetService<ConfigurationService>().
                    ParseConfiguration(JsonData);
                logger.Debug("myDouble:" + conf.GetConfigurationValue<Double>("myDouble"));
                logger.Debug("myString:" + conf.GetConfigurationValue<String>("myString"));
                logger.Debug("myInt:" + conf.GetConfigurationValue<Int32>("myInt"));
                logger.Debug("myBoolean:" + conf.GetConfigurationValue<Boolean>("myBoolean"));
            }
            Configurations config = null;

            if (JsonData != null && JsonData.Trim().Length > 0) {
                config = Configurations.CreateInstanceFromString(JsonData);
            }

            if (config != null) {
                this.RootVisual = new SilverChartPage();
            }
        }

        private void OnExit(object sender, EventArgs e) {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) {
            if (!System.Diagnostics.Debugger.IsAttached) {
                e.Handled = true;

                try {
                    string errorMsg = e.ExceptionObject.Message + @"\n" + e.ExceptionObject.StackTrace;
                    errorMsg = errorMsg.Replace("\"", "\\\"").Replace("\r\n", @"\n");

                    System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application: " + errorMsg + "\");");
                }
                catch (Exception) {
                }
            }
        }
    }
}